﻿using System.Web.Mvc;
using pbvs.Models.DomainModels;
using pbvs.Models.ViewModels;
using pbvs.Services;
using pbvs.Models;
using pbvs.Services.Interfaces;
using System.Linq;
using pbvs.Services.ServiceExtensions;

namespace pbvs.Controllers
{
    public class ManageController : Controller
    {
	    private readonly IFormElementService _formService;
	    private readonly IManageService _manageService;
		
	    public ManageController(IFormElementService formService, IManageService manageService)
	    {
		    _formService = formService;
		    _manageService = manageService;
	    }

        public ActionResult FormElement(string field)
        {
			return View(_formService.LoadViewModel(field));
        }

	    [HttpPost]
	    public ActionResult FormElement(FormElement elem)
	    {
			_formService.SaveFormElement(elem);
			return View(_formService.LoadViewModel(elem.Field));
	    }

	    public ActionResult SiteDefaults(int id = 0)
	    {
		    DefaultViewModel dvm = new DefaultViewModel {Defaults = _manageService.LoadDefaultsFromMemory()};
		    if (id > 0)
		    {
			    DefaultDomainModel def = _manageService.LoadDefaultsFromMemory().FirstOrDefault(d => d.Id == id);
			    if (def != null)
			    {
				    dvm.Id = def.Id;
				    dvm.Name = def.Name;
				    dvm.Value = def.Value;
			    }
		    }
		    return View(dvm);
	    }

		[HttpPost]
	    public ActionResult EditDefault(Default def)
	    {
		    return RedirectToAction("SiteDefaults", "Manage", new {id = _manageService.EditDefault(def.ToDomainModel())});
	    }

        public ActionResult Index()
        {
            return View();
        }
    }
}
